package com.pp.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pp.common.pojo.PostTag;
import com.pp.common.pojo.Tag;
import com.pp.web.mapper.PostTagMapper;
import com.pp.web.service.IPostTagService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PostTagServiceImpl extends ServiceImpl<PostTagMapper, PostTag> implements IPostTagService {

    @Override
    public List<PostTag> findByPostId(String postId) {
        QueryWrapper<PostTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PostTag::getPostId, postId);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<PostTag> findByTagId(String tagId) {
        QueryWrapper<PostTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PostTag::getTagId, tagId);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public void createPostTag(String postId, List<Tag> tags) {
        // 先删除当前 topicId 与其对应的所有 tagIds 记录
        this.baseMapper.delete(
            new LambdaQueryWrapper<PostTag>().eq(PostTag::getPostId, postId)
        );

        // 循环保存对应的 topic 与 tag 关联
        tags.forEach(tag -> {
            PostTag topicTag = new PostTag()
                .setPostId(postId)
                .setTagId(tag.getId());
            this.baseMapper.insert(topicTag);
        });
    }
}
